#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char* argv[]) {
    printf("=== GuDB MySQL Client Test ===\n");
    
    // Parse command line arguments
    uint16_t port = 3316;
    char* host = "127.0.0.1";
    
    if (argc > 1) {
        port = (uint16_t)atoi(argv[1]);
    }
    if (argc > 2) {
        host = argv[2]; 
    }
    
    printf("Connecting to GuDB server at %s:%u\n", host, port);
    
    // Create socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }
    
    // Set up server address
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    
    if (inet_pton(AF_INET, host, &server_addr.sin_addr) <= 0) {
        printf("❌ Invalid address: %s\n", host);
        close(sockfd);
        return 1;
    }
    
    // Connect to server
    printf("1. Attempting to connect...\n");
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect");
        printf("❌ Failed to connect to server\n");
        close(sockfd);
        return 1;
    }
    printf("✅ Connected to server successfully\n");
    
    // Read handshake packet
    printf("2. Reading handshake packet...\n");
    uint8_t buffer[1024];
    ssize_t bytes_read = recv(sockfd, buffer, sizeof(buffer), 0);
    
    if (bytes_read <= 0) {
        printf("❌ Failed to read handshake packet\n");
        close(sockfd);
        return 1;
    }
    
    printf("✅ Received handshake packet (%zd bytes)\n", bytes_read);
    
    // Print packet header (first 4 bytes are length + sequence)
    if (bytes_read >= 4) {
        uint32_t packet_length = buffer[0] | (buffer[1] << 8) | (buffer[2] << 16);
        uint8_t sequence_id = buffer[3];
        printf("   Packet length: %u, Sequence ID: %u\n", packet_length, sequence_id);
        
        // The payload starts at byte 4
        if (bytes_read >= 5) {
            uint8_t protocol_version = buffer[4];
            printf("   Protocol version: %u\n", protocol_version);
            
            // Server version string follows
            if (bytes_read > 5) {
                printf("   Server version: ");
                for (int i = 5; i < bytes_read && buffer[i] != 0; i++) {
                    printf("%c", buffer[i]);
                }
                printf("\n");
            }
        }
    }
    
    printf("3. Connection established - basic MySQL protocol test passed!\n");
    
    // Close connection
    close(sockfd);
    printf("✅ Connection closed\n");
    
    printf("\n=== MySQL Protocol Test Complete ===\n");
    return 0;
}